﻿/* ==============================================================================
*
*   Copyright (c) 2010, Pierre Favier
*   All rights reserved.
*
*   NTasking is free software: you can redistribute it and/or modify it
*   under the terms of the GNU General Public License as published by the
*   Free Software Foundation.
*
*   Redistribution and use in source and binary forms, with or without
*   modification, are permitted provided that the following conditions
*   are met:
*
*   -   Redistributions of source code must retain the above copyright notice,
*       this list of conditions and the following disclaimer.
*
*   -   Redistributions in binary form must reproduce the above
*       copyright notice, this list of conditions and the following
*       disclaimer in the documentation and/or other materials
*       provided with the distribution.
*
*   THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
*   WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
*   OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
*   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
*   BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
*   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
*   TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
*   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
*   ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
*   TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
*   THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
*   SUCH DAMAGE.
*
* ============================================================================== */

using System.Collections.Generic;
using System.Threading;

namespace NTasking.Internals
{

    /// <summary>
    /// Implements the methods of <see cref="ThreadWrapper"/> linked to the thread priority.
    /// </summary>
    internal partial class ThreadWrapper
    {

        #region Fields

        /// <summary>
        /// The priority which has been requested for this instance. This value can be different from
        /// the effective priority that the thread has due to priority inheritance rules.
        /// </summary>
        private ThreadPriority _basePriority;

        /// <summary>
        /// A stack used to store the priorities successively inherited by this instance.
        /// </summary>
        private readonly Stack<ThreadPriority> _inheritedPriorities = new Stack<ThreadPriority>();

        /// <summary>
        /// A lock used to protected against concurrent access.
        /// </summary>
        private readonly object _priorityLock = new object();

        #endregion


        #region Properties

        /// <summary>
        /// Gets the current priority of this instance.
        /// </summary>
        /// <value>The current priority of this instance.</value>
        public ThreadPriority CurrentPriority
        {
            get { return Thread.Priority; }
        }


        /// <summary>
        /// Gets or sets the priority which has been requested for this instance. This value can be different from
        /// the effective priority that the thread has due to priority inheritance rules..
        /// </summary>
        /// <value>The priority which has been requested.</value>
        public ThreadPriority Priority
        {
            get { return _basePriority; }
            set
            {
                if (_basePriority == value)
                    return;

                _basePriority = value;

                lock (_priorityLock)
                {
                    SetCurrentPriority(true);
                }
            }
        }


        /// <summary>
        /// Gets the priority currently inherited by this instance.
        /// </summary>
        /// <value>The inherited priority.</value>
        private ThreadPriority InheritedPriority
        {
            get
            {
                return _inheritedPriorities.Count == 0 ?
                                ThreadPriority.Lowest :
                                _inheritedPriorities.Peek();
            }
        }


        #endregion


        #region Methods

        /// <summary>
        /// Computes the maximum of two priorities.
        /// </summary>
        /// <param name="left">The first priority.</param>
        /// <param name="right">The second priority.</param>
        /// <returns>The maximum value of <paramref name="left"/> and <paramref name="right"/></returns>
        private static ThreadPriority Max(ThreadPriority left, ThreadPriority right)
        {
            return left > right ? left : right;
        }


        /// <summary>
        /// Sets the current priority of this instance, taking into account the requested priority and
        /// the inherited priority.
        /// </summary>
        private void SetCurrentPriority(bool requeueCalls)
        {
            try { }
            finally
            {
                // Do everything within a finally to protect against abortion of executing task

                using (NoAbort())
                {
                    ThreadPriority oldPriority = Priority;
                    // New priority is the max of the requested priority and inherited priority
                    ThreadPriority newPriority = Max(Priority, InheritedPriority);

                    if (oldPriority != newPriority)
                    {
                        Priority = newPriority;

                        if (requeueCalls &&
                            Settings.QueueingPolicy == QueueingPolicy.PriorityQueueing)
                        {
                            // If the current thread is waiting for completion of entry call(s) and the entry queueing policy
                            // depends on the caller priority, change the position of the current instance in the queue(s) on which
                            // it is waiting

                            MethodCall[] callsWaitingForCompletion;

                            lock (_priorityLock)
                                callsWaitingForCompletion = _callsWaitingForCompletion.ToArray();

                            foreach (MethodCall call in callsWaitingForCompletion)
                                if (newPriority < oldPriority)
                                    call.Target.Owner.PriorityLowered(call);
                                else
                                    call.Target.Owner.PriorityRaised(call);
                        }
                    }
                }
            }
        }


        /// <summary>
        /// Starts the inheritance of a priority.
        /// </summary>
        /// <param name="priority">The new inherited priority.</param>
        internal void StartPriorityInherit(ThreadPriority priority)
        {
            lock (_priorityLock)
            {
                ThreadPriority oldInherited = InheritedPriority;
                ThreadPriority newInherited = Max(oldInherited, priority);

                _inheritedPriorities.Push(newInherited);

                if (oldInherited != newInherited)
                    SetCurrentPriority(false);
            }
        }


        /// <summary>
        /// End the inheritance of a priority.
        /// </summary>
        internal void EndPriorityInherit()
        {
            lock (_priorityLock)
            {
                ThreadPriority oldInherited = InheritedPriority;

                if (_inheritedPriorities.Count > 0)
                    _inheritedPriorities.Pop();

                ThreadPriority newInherited = InheritedPriority;

                if (oldInherited != newInherited)
                    SetCurrentPriority(false);
            }
        }

        #endregion

    }

}
